package com.yunchao.library.socket.model.connection

import com.yunchao.library.socket.constants.Values
import com.yunchao.library.socket.extensions.toReadOnlyBuffer
import com.yunchao.library.socket.utils.ValidationUtils
import java.nio.ByteBuffer
import java.nio.ByteOrder

data class AccessRequest(
    val session: Int = Values.DEFAULT_SESSION,
    val datetime: Long
) {
    init {
        ValidationUtils.validateSession(session)
    }

    fun toByteArray(): ByteArray {
        return ByteBuffer.allocate(9)
            .order(ByteOrder.BIG_ENDIAN)
            .put(session.toByte())
            .putLong(datetime)
            .array()
    }

    companion object {
        fun fromByteArray(bytes: ByteArray): AccessRequest {
            val buffer = bytes.toReadOnlyBuffer()
            return AccessRequest(
                session = buffer.get().toInt() and 0xFF,
                datetime = buffer.long
            )
        }
    }
}